package jwtTool

import (
	"CommonsProject/conf"
	"CommonsProject/models/systemModel"
	"CommonsProject/pkg/tools/redisTool"
	"context"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var securityKey string = conf.GlobalConfig.Jwt.SecurityKey

// GeneratorToken 生成Token
func GeneratorToken(sub any) string {

	t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"sub": sub,
		"iat": time.Now(),
		"exp": time.Now().Add(time.Hour * 24),
	})

	token, err := t.SignedString(securityKey)
	if err != nil {
		panic(errors.New("密钥签名失败！"))
	}
	return token
}

// ParseToken 解析token
func ParseToken(token string) systemModel.SysUser {
	parse, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		//检验加密算法是否正确
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("token不合法！")
		}

		//返回加密时的密钥
		return []byte(securityKey), nil
	})

	if err != nil {
		panic(fmt.Errorf("token不合法！"))
	}

	//校验签名时间
	expirationTime, err := parse.Claims.GetExpirationTime()
	if err != nil {
		panic(fmt.Errorf("token已过期：%s", err.Error()))
	}
	if expirationTime.Before(time.Now()) {
		panic(fmt.Errorf("token已过期"))
	}

	userId, _ := parse.Claims.GetSubject()
	background := context.Background()
	var user systemModel.SysUser
	if redisTool.ClientRedis.Get(background, fmt.Sprintf("%s:%s", redisTool.LOGIN_USER_REDIS_PREFIX, userId)).Scan(&user) != nil {
		panic(fmt.Errorf("解析redis失败！"))
	}
	return user
}
